package com.phpxiu.app.view;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.phpxiu.app.api.OnDialogClickListener;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.BuildConfig;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.event.OnLanguageEvent;
import com.phpxiu.app.model.list.Language;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.OKHttpResponseModel;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.supports.swichbutton.SwitchButton;
import com.phpxiu.app.utils.CacheManager;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.dialog.LanguageOptionsWin;
import com.tencent.TIMCallBack;
import com.tencent.TIMManager;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by WuJinZhou on 2016/6/6.
 */
public class UserSetting extends UIBase implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{
    public final static String TAG="UserSetting";
    public final static int HANDLER_MSG_SET_CACHE_MSG=0x1;
    public final static String KKY_USER_LANGUAGE_CONFIG="ky_current_language_config";
    public final static String KKY_CURRENT_LANGUAGE_CODE="kky_current_language_code";
    private TextView cacheSizeTv,languageView;
    private boolean isLogin=true;
    private Button loginOutBtn;
    private SharedPreferences sp;
    private int mCurrentLanguage=0;
    private LanguageOptionsWin languageOptionsWin;
    public List<Language> LANGUAGES=new ArrayList<Language>();

    private SwitchButton allBtn;
    private SharedPreferences mSp;
    private boolean isReceive=true;
    private TextView versionView;
    private View outCoverView;//退出登录状态
    private AnimationDrawable outing;//退出登录动画

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LANGUAGES.clear();
        LANGUAGES.add(new Language(0,getString(R.string.language_auto)));
        LANGUAGES.add(new Language(1,getString(R.string.language_chinese)));
        LANGUAGES.add(new Language(2,getString(R.string.language_english)));
        sp=getSharedPreferences(KKY_USER_LANGUAGE_CONFIG,MODE_PRIVATE);
        setContentView(R.layout.user_setting);
        cacheSizeTv=(TextView)findViewById(R.id.cache_size);
        cacheSizeTv.setText("Reading...");
        Thread t=new Thread(new CalculateCacheSize());
        t.start();
        findViewById(R.id.top_bar_back_btn).setOnClickListener(this);
        findViewById(R.id.my_blacklist_link).setOnClickListener(this);
        findViewById(R.id.push_manage_link).setOnClickListener(this);
        mSp=getSharedPreferences(Constants.USER_INFO,MODE_PRIVATE);
        isReceive=mSp.getBoolean(Constants.USER_NOTICE_SETTING,true);
        allBtn=(SwitchButton)findViewById(R.id.set_all_notice_switch_btn);
        allBtn.setChecked(isReceive);
        allBtn.setOnCheckedChangeListener(this);
        findViewById(R.id.clear_cache_link).setOnClickListener(this);
        findViewById(R.id.language_settings_link).setOnClickListener(this);
        mCurrentLanguage=sp.getInt(KKY_CURRENT_LANGUAGE_CODE, 0);
        LANGUAGES.get(mCurrentLanguage).setSelected(true);
        languageView=(TextView)findViewById(R.id.current_language);
        languageView.setText(LANGUAGES.get(mCurrentLanguage).getName());
        MySelfInfo.getInstance().getCache(this);
        isLogin=MySelfInfo.getInstance().getId()!=null;
        loginOutBtn = (Button) findViewById(R.id.login_out_btn);
        loginOutBtn.setOnClickListener(this);
        if(isLogin) {
            loginOutBtn.setVisibility(View.VISIBLE);
        }else{
            loginOutBtn.setVisibility(View.GONE);
        }
        outCoverView=findViewById(R.id.logout_cover_view);
        outing=(AnimationDrawable)findViewById(R.id.logout_view).getBackground();
        versionView=(TextView)findViewById(R.id.version_info);
        versionView.setText(String.format(getString(R.string.ui_settings_version_title),BuildConfig.VERSION_NAME));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.top_bar_back_btn:
                onBackPressed();
                break;
            case R.id.my_blacklist_link:
                Intent blacklist=new Intent(this,MyBlackList.class);
                startActivity(blacklist);
                break;
            case R.id.clear_cache_link:
                onClearCache();
                break;
            case R.id.language_settings_link:
                showLanguageOptions();
                break;
            case R.id.login_out_btn:
                onLoginOut();
                break;
            default:
                break;
        }
    }

    @Override
    public void handleMsg(Message msg) {
        switch (msg.what){
            case HANDLER_MSG_SET_CACHE_MSG:
                cacheSizeTv.setText(msg.obj.toString());
                break;
        }
    }

    /**
     * 清除缓存
     */
    private void onClearCache(){
        interactiveDialog(getString(R.string.ui_settings_cache_label), getString(R.string.ui_settings_cache_description),new OnDialogClickListener(){
            @Override
            public void onOk() {
                clearCache();
            }

            @Override
            public void onCancel() {
            }
        });
    }

    /**
     * 显示语言显示选项
     */
    private void showLanguageOptions(){
        if(languageOptionsWin==null){
            languageOptionsWin=new LanguageOptionsWin(this,mCurrentLanguage);
            languageOptionsWin.getWindow().getAttributes().width=(int) KKYApp.getInstance().screenWidth;
        }
        languageOptionsWin.show();
    }

    /**
     * 切换语言
     * @param language
     */
    public void switchLanguage(int language){
        mCurrentLanguage=language;
        for (Language l:LANGUAGES){
            l.setSelected(false);
        }
        LANGUAGES.get(language).setSelected(true);
        if(sp==null){
            sp=getSharedPreferences(KKY_USER_LANGUAGE_CONFIG,MODE_PRIVATE);
        }
        sp.edit().putInt(KKY_CURRENT_LANGUAGE_CODE,language).commit();
        EventBus.getDefault().post(new OnLanguageEvent());
        finish();
    }

    /**
     * 退出登录
     */
    private void onLoginOut(){
        //http://kkylive.phpxiu.com/api/account/logout

        interactiveDialog(getString(R.string.ui_settings_logout_title), getString(R.string.ui_settings_logout_desc),new OnDialogClickListener(){
            @Override
            public void onOk() {
                if(outCoverView!=null){
                    outCoverView.setVisibility(View.VISIBLE);
                }
                if(outing!=null){
                    outing.start();
                }
                TIMManager.getInstance().logout(new TIMCallBack() {
                    @Override
                    public void onError(int i, String s) {
                        if (KKYUtil.DEBUG) {
                            Toast.makeText(UserSetting.this, "IM登出失败：" + i + "@" + s, Toast.LENGTH_LONG).show();
                        }
                        loginOut();
                    }

                    @Override
                    public void onSuccess() {
                        if (KKYUtil.DEBUG) {
                            Toast.makeText(UserSetting.this, "IM登出成功", Toast.LENGTH_LONG).show();
                        }
                        loginOut();
                    }
                });

            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * 退出登录
     */
    private void loginOut(){
        stopAVSDK();
        MySelfInfo.getInstance().clearCache(UserSetting.this);
        MySelfInfo.getInstance().loginOut();
        OKHttpParam param=OKHttpParam.builder(false);
        OKHttp.post(HttpConfig.API_LOGIN_OUT, param.jsonParam(), TAG, new OKHttpUIHandler(OKHttpResponseModel.class) {
            @Override
            public void onSuccess(Object model) {
                OKHttpResponseModel m = (OKHttpResponseModel) model;
                KKYUtil.log("退出登录成功结果：" + m.getResponseStr());
                logoutComplete(true);
            }

            @Override
            public void onErr(String errMsg) {
                KKYUtil.log("退出登录失败：" + errMsg);
                logoutComplete(false);
            }
        });
    }

    /**
     * 登出完成
     */
    final private void logoutComplete(boolean isSuccess){
        if(outCoverView!=null&&outCoverView.getVisibility()==View.VISIBLE){
            outCoverView.setVisibility(View.INVISIBLE);
        }
        if(outing!=null){
            outing.stop();
        }
        Intent login=new Intent(UserSetting.this,Login.class);
        if(isSuccess){
            Toast.makeText(UserSetting.this, "登出成功", Toast.LENGTH_LONG).show();
            login.putExtra(BaseLogin.LOGIN_ACTION,BaseLogin.LOG_OUT);
        }else{
            login.putExtra(BaseLogin.LOGIN_ACTION,BaseLogin.FORCE_LOG_OUT);
        }
        startActivity(login);
    }
    /**
     * 反初始化AVADK
     */
    public void stopAVSDK() {
        QavsdkControl.getInstance().stopContext();
    }
    /**
     * 计算缓存
     */
    class  CalculateCacheSize implements Runnable{
        @Override
        public void run() {
            Message msg=handler.obtainMessage();
            msg.what=HANDLER_MSG_SET_CACHE_MSG;
            msg.obj=cacheSize();
            handler.sendMessage(msg);
        }
    }

    /**
     * 计算缓存
     * 1.Http请求缓存 H
     * 2.ImageLoader图片加载缓存
     * 3.Fresco 图片缓存
     * 4.webView缓存
     * 5.其它下载缓存文件
     */
    public String cacheSize(){
        long size=0;
        String cacheDir=getCacheDir().getPath();
        try {
            long innerCacheSize= CacheManager.getFolderSize(getCacheDir());
            size+=innerCacheSize;
            KKYUtil.log(TAG,"内部临时缓存:"+innerCacheSize);
            String fileDir=getFilesDir().getPath();
            long innerFileCache=CacheManager.getFolderSize(getFilesDir());
            size+=innerFileCache;
            KKYUtil.log(TAG,"内部文件缓存:"+innerFileCache);
            if (1==2&& Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String extraCacheDir=getExternalCacheDir().getPath();
                long extraCache=CacheManager.getFolderSize(getExternalCacheDir());
                size+=extraCache;
                KKYUtil.log(TAG,"外部临时缓存:"+extraCache);
                String extraFileDir_DCIM=getExternalFilesDir(Environment.DIRECTORY_DCIM).getPath();
                long extraDCIMSize=CacheManager.getFolderSize(getExternalFilesDir(Environment.DIRECTORY_DCIM));
                size+=extraDCIMSize;
                KKYUtil.log(TAG,"外部DCIM文件缓存:"+extraDCIMSize);
                String extraFileDir_MOVIE=getExternalFilesDir(Environment.DIRECTORY_MOVIES).getPath();
                long extraMOVIESSize=CacheManager.getFolderSize(getExternalFilesDir(Environment.DIRECTORY_MOVIES));
                KKYUtil.log(TAG,"外部MOVIES文件缓存:"+extraMOVIESSize);
                size+=extraMOVIESSize;
                String extraFileDir_ALARMS=getExternalFilesDir(Environment.DIRECTORY_ALARMS).getPath();
                long extraALARMSSize=CacheManager.getFolderSize(getExternalFilesDir(Environment.DIRECTORY_ALARMS));
                KKYUtil.log(TAG,"外部ALARMS文件缓存:"+extraALARMSSize);
                size+=extraALARMSSize;
                String extraFileDir_DOC=getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath();
                long extraDOCSize=CacheManager.getFolderSize(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS));
                KKYUtil.log(TAG,"外部DOC文件缓存:"+extraDOCSize);
                size+=extraDOCSize;
                String extraFileDir_DOWN=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getPath();
                long extraDOWNSize=CacheManager.getFolderSize(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS));
                KKYUtil.log(TAG,"外部DOWN文件缓存:"+extraDOWNSize);
                size+=extraDOWNSize;
                String extraFileDir_PIC=getExternalFilesDir(Environment.DIRECTORY_PICTURES).getPath();
                long extraPICSize=CacheManager.getFolderSize(getExternalFilesDir(Environment.DIRECTORY_PICTURES));
                KKYUtil.log(TAG,"外部PIC文件缓存:"+extraPICSize);
                size+=extraPICSize;
                String extraFileDir_MUSIC=getExternalFilesDir(Environment.DIRECTORY_MUSIC).getPath();
                long extraMUSICSize=CacheManager.getFolderSize(getExternalFilesDir(Environment.DIRECTORY_MUSIC));
                KKYUtil.log(TAG,"外部MUSIC文件缓存:"+extraMUSICSize);
                size+=extraMUSICSize;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CacheManager.getFormatSize(size);
    }

    /**
     * 清除缓存
     */
    public void clearCache(){
        KKYUtil.log(TAG,"清除文件缓存....");
        CacheManager.deleteFolderFile(getCacheDir().getPath(),true);
        CacheManager.deleteFolderFile(getFilesDir().getPath(),true);
        CacheManager.deleteFolderFile(getExternalCacheDir().getPath(),true);
        cacheSizeTv.setText("0.0M");
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        mSp.edit().putBoolean(Constants.USER_NOTICE_SETTING,isChecked).commit();
        KKYApp.getInstance().setShowNotice(isChecked);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
